package myjavax.security.sasl;

import java.security.Provider;
import java.security.Security;
import java.util.Map;
import myjavax.security.auth.callback.CallbackHandler;

public class Sasl {
    public static SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException {
        for (String mechName : mechanisms) {
            if (mechName == null) {
                throw new NullPointerException("Mechanism name cannot be null");
            }
            if (mechName.length() != 0) {
                String mechFilter = "SaslClientFactory." + mechName;
                Provider[] provs = Security.getProviders(mechFilter);
                int j = 0;
                while (provs != null && j < provs.length) {
                    String className = provs[j].getProperty(mechFilter);
                    if (className != null) {
                        SaslClientFactory fac = (SaslClientFactory) loadFactory(provs[j], className);
                        if (fac != null) {
                            SaslClient mech = fac.createSaslClient(new String[]{mechanisms[i]}, authorizationId, protocol, serverName, props, cbh);
                            if (mech != null) {
                                return mech;
                            }
                        } else {
                            continue;
                        }
                    }
                    j++;
                }
            }
        }
        return null;
    }

    private static Object loadFactory(Provider p, String className) throws SaslException {
        try {
            return Class.forName(className, true, p.getClass().getClassLoader()).newInstance();
        } catch (ClassNotFoundException e) {
            throw new SaslException("Cannot load class " + className, e);
        } catch (InstantiationException e2) {
            throw new SaslException("Cannot instantiate class " + className, e2);
        } catch (IllegalAccessException e3) {
            throw new SaslException("Cannot access class " + className, e3);
        } catch (SecurityException e4) {
            throw new SaslException("Cannot access class " + className, e4);
        }
    }
}
